from odoo import models, fields, api, _
from odoo.exceptions import UserError
import calendar
import logging


_logger = logging.getLogger(__name__)


class IrSequenceMonth(models.TransientModel):
    _name = "ir.sequence.month"

    def _default_id(self):
        return self._context.get('active_id')

    ir_sequence_id = fields.Many2one(
        'ir.sequence', string="序列号", required=True, default=_default_id)

    start_date = fields.Date('开始时间')
    stop_date = fields.Date('结束时间')

    def get_month_range(self, start_day, end_day):
        months = (end_day.year - start_day.year) * \
            12 + end_day.month - start_day.month
        month_range = ['%s-%s' % (start_day.year + mon//12, mon % 12+1)
                       for mon in range(start_day.month-1, start_day.month + months)]
        result = []
        for month in month_range:
            tem_str = month.split('-')
            end = calendar.monthrange(int(tem_str[0]), int(tem_str[1]))[1]
            start = str(tem_str[0])+'-' + str(tem_str[1]).zfill(2) + '-01'
            end = str(tem_str[0])+'-' + \
                str(tem_str[1]).zfill(2) + '-' + str(end)
            result.append((start, end))
        return result

    @api.one
    def generate(self):
        tem = self.get_month_range(self.start_date, self.stop_date)
        for month in tem:
            have = False
            for sub_sequence in self.ir_sequence_id.date_range_ids:
                # _logger.info(sub_sequence.number_next_actual)
                if month[0] == sub_sequence.date_from.strftime("%Y-%m-%d") and month[1] == sub_sequence.date_to.strftime("%Y-%m-%d"):
                    have = True
                    break
            if(have == False):
                self.ir_sequence_id.write({'date_range_ids': [(
                    0, 0, {'date_from': month[0], 'date_to':month[1], 'number_next_actual':1})]})
